import express from 'express';
import {
  submitSighting,
  getPostSightings,
  getPostSightingsPublic,
  getSightingById,
  verifySighting,
  getAllSightings,
  deleteSighting,
  uploadSightingPhoto,
  getSightingStats
} from '../controllers/sightingController.js';
import { authenticateToken, authenticateAdmin } from '../utils/jwt.js';
import { validateRequest, sightingSchema, paginationSchema } from '../utils/validation.js';
import { uploadSightingPhoto as uploadMiddleware } from '../utils/upload.js';
import Joi from 'joi';

const router = express.Router();

// 线索验证规则
const sightingValidation = validateRequest(sightingSchema, 'body');

// 分页验证中间件
const paginationValidation = validateRequest(paginationSchema, 'query');

// 线索验证状态更新规则
const verificationSchema = Joi.object({
  is_verified: Joi.boolean()
    .required()
    .messages({
      'any.required': '验证状态是必填项'
    })
});
const verificationValidation = validateRequest(verificationSchema, 'body');

/**
 * @route POST /api/sightings
 * @desc 提交目击线索（匿名）
 * @access Public
 */
router.post('/', uploadMiddleware, sightingValidation, submitSighting);

/**
 * @route POST /api/sightings/upload
 * @desc 上传线索照片
 * @access Public
 */
router.post('/upload', uploadMiddleware, uploadSightingPhoto);

/**
 * @route GET /api/sightings/all
 * @desc 获取所有线索列表（管理员用）
 * @access Private (Admin)
 */
router.get('/all', authenticateAdmin, paginationValidation, getAllSightings);

/**
 * @route GET /api/sightings/stats
 * @desc 获取线索统计信息（管理员用）
 * @access Private (Admin)
 */
router.get('/stats', authenticateAdmin, getSightingStats);

/**
 * @route GET /api/sightings/post/:postId/public
 * @desc 获取帖子的线索列表（公开访问）
 * @access Public
 */
router.get('/post/:postId/public', paginationValidation, getPostSightingsPublic);

/**
 * @route GET /api/sightings/post/:postId
 * @desc 获取帖子的线索列表（仅帖子作者可见）
 * @access Private (User - 仅帖子作者)
 */
router.get('/post/:postId', authenticateToken, paginationValidation, getPostSightings);

/**
 * @route GET /api/sightings/:id
 * @desc 根据ID获取线索详情（仅帖子作者可见）
 * @access Private (User - 仅帖子作者)
 */
router.get('/:id', authenticateToken, getSightingById);

/**
 * @route PATCH /api/sightings/:id/verify
 * @desc 验证线索（标记为有效/无效）
 * @access Private (User - 仅帖子作者)
 */
router.patch('/:id/verify', authenticateToken, verificationValidation, verifySighting);

/**
 * @route DELETE /api/sightings/:id
 * @desc 删除线索（管理员用）
 * @access Private (Admin)
 */
router.delete('/:id', authenticateAdmin, deleteSighting);

export default router;
